package com.aizuda.boot.modules.business.longterm.service.impl;

import com.aizuda.boot.modules.business.contract.entity.ContractTypeEntity;
import com.aizuda.boot.modules.business.longterm.domain.entity.LongTermContract;
import com.aizuda.boot.modules.business.longterm.domain.response.LongTermDetailVO;
import com.aizuda.boot.modules.business.longterm.domain.response.LongTermVo;
import com.aizuda.boot.modules.business.longterm.domain.resquest.LongTermSaveDTO;
import com.aizuda.boot.modules.business.longterm.domain.resquest.LongTermUpdateDTO;
import com.aizuda.boot.modules.business.longterm.mapper.LongTermContractMapper;
import com.aizuda.boot.modules.business.longterm.service.LongTermContractService;
import com.aizuda.boot.modules.business.performance.mapper.ContractTypeMapper;
import com.aizuda.core.api.ApiAssert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Author sangyirong
 * @ClassName LongTermContractServiceImpl
 * @Version 1.0
 * @Date 2025/7/7 16:05
 */
@Service
public class LongTermContractServiceImpl extends ServiceImpl<LongTermContractMapper, LongTermContract> implements LongTermContractService {

    @Resource
    private ContractTypeMapper contractTypeMapper;

    @Override
    public boolean saveLongTermContract(LongTermSaveDTO dto) {
        ApiAssert.fail(null == dto, "参数为空");
        ApiAssert.fail(null == dto.getDeadline() || null == dto.getUnit(), "时限为设置");
        LongTermContract contract = new LongTermContract();
        contract.setCode(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
        BeanUtils.copyProperties(dto, contract);
        this.save(contract);
        List<Integer> typeId = dto.getTypeId();
        contractTypeMapper.update(Wrappers.<ContractTypeEntity>lambdaUpdate()
                .set(ContractTypeEntity::getLongTermId, contract.getId())
                .in(ContractTypeEntity::getId, typeId));
        return true;
    }

    @Override
    public LongTermDetailVO queryDetail(Long id) {
        ApiAssert.fail(null == id, "参数为空");
        LongTermContract contract = this.getById(id);
        ApiAssert.fail(null == contract, "长期合同规则不存在");
        LongTermDetailVO result = new LongTermDetailVO();
        BeanUtils.copyProperties(contract, result);
        List<Integer> typeIds = contractTypeMapper.selectList(Wrappers.<ContractTypeEntity>lambdaQuery()
                        .eq(ContractTypeEntity::getLongTermId, id)
                        .select(ContractTypeEntity::getId))
                .stream().map(ContractTypeEntity::getId)
                .collect(Collectors.toList());
        result.setTypeId(typeIds);
        return result;
    }

    @Override
    public List<LongTermVo> listVO() {
        // 获取所有长期合同
        List<LongTermContract> contracts = this.list();
        
        // 转换为VO列表
        return contracts.stream().map(contract -> {
            LongTermVo vo = new LongTermVo();
            vo.setId(contract.getId());
            vo.setCode(contract.getCode());
            vo.setDeadline(contract.getDeadline());
            vo.setUnit(contract.getUnit());
            
            // 获取关联的合同类型名称列表
            List<String> typeNames = contractTypeMapper.selectList(Wrappers.<ContractTypeEntity>lambdaQuery()
                            .eq(ContractTypeEntity::getLongTermId, contract.getId())
                            .select(ContractTypeEntity::getTypeName))
                    .stream()
                    .map(ContractTypeEntity::getTypeName)
                    .collect(Collectors.toList());
            vo.setType(typeNames);
            
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean updateLongTermContract(LongTermUpdateDTO dto) {
        ApiAssert.fail(null == dto, "参数为空");
        ApiAssert.fail(null == dto.getId(), "长期合同ID不能为空");
        ApiAssert.fail(null == dto.getDeadline() || null == dto.getUnit(), "时限为设置");
        
        // 验证长期合同是否存在
        LongTermContract existContract = this.getById(dto.getId());
        ApiAssert.fail(null == existContract, "长期合同不存在");
        
        // 更新长期合同基本信息
        LongTermContract contract = new LongTermContract();
        BeanUtils.copyProperties(dto, contract);
        this.updateById(contract);
        
        // 先清除原有的合同类型关联 - 将原来关联到此长期合同的合同类型的longTermId设为null
        contractTypeMapper.update(Wrappers.<ContractTypeEntity>lambdaUpdate()
                .set(ContractTypeEntity::getLongTermId, null)
                .eq(ContractTypeEntity::getLongTermId, dto.getId()));
        
        // 设置新的合同类型关联
        List<Integer> typeIds = dto.getTypeId();
        if (typeIds != null && !typeIds.isEmpty()) {
            contractTypeMapper.update(Wrappers.<ContractTypeEntity>lambdaUpdate()
                    .set(ContractTypeEntity::getLongTermId, dto.getId())
                    .in(ContractTypeEntity::getId, typeIds));
        }
        
        return true;
    }

    @Override
    public boolean removeLongTermContract(Long id) {
        ApiAssert.fail(null == id, "长期合同ID不能为空");
        
        // 验证长期合同是否存在
        LongTermContract existContract = this.getById(id);
        ApiAssert.fail(null == existContract, "长期合同不存在");
        
        // 先清除关联的合同类型 - 将原来关联到此长期合同的合同类型的longTermId设为null
        contractTypeMapper.update(Wrappers.<ContractTypeEntity>lambdaUpdate()
                .set(ContractTypeEntity::getLongTermId, null)
                .eq(ContractTypeEntity::getLongTermId, id));
        
        // 删除长期合同记录
        return this.removeById(id);
    }
}
